<!DOCTYPE html>
<script>
  let device;
  window.onmessage = messageEvent => {
    if (messageEvent.data === 'RequestAndConnect') {
      navigator.bluetooth.requestDevice({
        filters: [{services: ['heart_rate']}]
      })
      .then(device => device.gatt.connect())
      .then(gattServer => {
        device = gattServer.device;
        parent.postMessage('Connected', '*');
      }).catch(err => {
        console.error(err);
        parent.postMessage('FAIL: ' + err, '*');
      });
    } else if (messageEvent.data === 'StartNotifications') {
      device.gatt.getPrimaryService('heart_rate')
        .then(service => service.getCharacteristic('heart_rate_measurement'))
        .then(char => char.startNotifications())
        .then(char => {
          char.addEventListener('characteristicvaluechanged', function() {});
          parent.postMessage('NotificationsStarted', '*');
        });
    }
  };
  parent.postMessage("Ready", "*");
</script>
